<?php 
defined('BASEPATH') OR exit('No direct script access allowed');

class CI_Crontab_email{
	var $CI;
	public function __construct( ){
		$this->CI =& get_instance();
	}
	
	function cronUpdate($unique_code , $callback_func, $list_args, $time_proc_array){
		foreach($time_proc_array as $time){
			$this->CI->db->set('unique_code',$unique_code);
			$this->CI->db->set('callback_func',$callback_func);
			$this->CI->db->set('time_proc',$time);
			$this->CI->db->set('status_proc','pending');
			$this->CI->db->set('list_args',$list_args);
			
			$this->CI->db->insert(TBL_CRONTAB_EMAIL);
		}	
	}	
	
	function cronExec()
	{
		$this->CI->load->helper('file');
		$this->CI->load->library('email_sender');
		$timenow = time();
		$pending_cron = $this->CI->db->where("status_proc LIKE 'pending' AND time_proc < $timenow")->get(TBL_CRONTAB_EMAIL)->result();
		$first = $this->CI->db->query("SELECT * FROM ".TBL_CRONTAB_EMAIL." LIMIT 1")->result();
		
		$execedTime = intval( read_file('uploads/timeexec.txt') );
		if($timenow > $execedTime + 500){ // after 1000 second if crontab email not run will be update status over progress.
			$unsent = $this->CI->db->query("SELECT * FROM ".TBL_CRONTAB_EMAIL." WHERE time_proc < $timenow AND status_proc LIKE 'pending' ")->result();
			if(!empty($unsent)){
				$this->CI->db->where('id', $unsent[0]->id )->update(TBL_CRONTAB_EMAIL, array('email_proc'=>'sleeping', 'status_proc'=> 'done'));
			}
			//$this->CI->db->where('time_proc >', $timenow)->update(TBL_CRONTAB_EMAIL, array('email_proc'=>'sleeping', 'status_proc'=> 'pending'));
		}
		
		if( !empty($first) AND $first[0]->email_proc == 'sleeping' ){
			$this->CI->db->where('id', $first[0]->id)->update(TBL_CRONTAB_EMAIL, array('email_proc'=>'sending'));
			
			foreach($pending_cron as $cron){
				call_user_func_array( array($this->CI->email_sender, $cron->callback_func) , explode(',', $cron->list_args) );		
				$this->CI->db->where('id',$cron->id)->update(TBL_CRONTAB_EMAIL , array('status_proc'=> 'done'));
			}	
			
			$this->CI->db->where('id', $first[0]->id)->update(TBL_CRONTAB_EMAIL, array('email_proc'=>'sleeping'));
			write_file('uploads/timeexec.txt', time());
		}
	}
	
}	